<?php 
namespace MyPhp;
dispatch_request();
//记录访问次数 也可以使用HTML5的localStorage来实现
global $count;
if(!isset($_COOKIE["visitcount"]))
{
    setcookie("visitcount", $count, time()+3600*24);
}
else
{
    $count = $_COOKIE['visitcount']+1;
    setcookie("visitcount", $count, time()+3600*24);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Hello world</title>
    <script src="js/jquery-1.11.3.js"></script>
    <script src="js/jquery-ui.js"></script>
    <link rel="stylesheet" href="css/jquery-ui.css">
    <style>
	body
    {
        font-size: 100%;/*use em set font size*/
    }
    .ui-tabs-nav
    {
        font-size: 1.3em;
        background-color: LightGreen;
        text-align: center;
    }
    .ui-tabs-anchor
    {
        background-color: #98bf21;
    }
    .ui-tabs
    {
        padding: 0;
    }
    .ui-tabs .ui-tabs-panel
    {
        font-size: 1.2em;
        color: RoyalBlue;
        background-color: LavenderBlush;
        padding: 20px;
    }
    .ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited
    {
        font-weight: bold;
        color: Navy;
    }

    input,button
    {
        font-size: 0.8em;
        color: RoyalBlue;
    }
	</style>
</head>
<body>
<?php
define("GREETING","Welcome to my first php demo");
$str = "我的第一段 PHP 脚本！";
$a = 6;
$b = 9;
function hello($b){
    global $str;
    echo "<p>Hello world! $str,",strlen($str),"</p>";
    $a = &$GLOBALS['a'];
    $a = 0x4a;
    if($b<100)
    {
        $c = round($a/$b+$b,3);
        print "计算变量的值"."$a/$b+$b=$c<br>";
    }
    
    //数组
    $cars = array("Volvo","BMW","Toyota");
    print 'var_dump($cars)=';var_dump($cars);
    $len = count($cars);
    for($x=0;$x<$len;++$x)//or foreach($cars as $x)
    {
        echo "<br>",$cars[$x];
    }
    
    //关联数组
    $heroes = array("剑姬"=>"菲奥娜","剑圣"=>"易","剑豪"=>"亚索","剑魔"=>"亚托克斯");
    ksort($heroes);
    foreach($heroes as $hero=>$name)
    {
        echo "<br>","英雄：".$hero.", 名字：".$name;
    }
}

function test_class(){
    //类
    echo "<p><b>测试类,对象,接口,Traits：</b></p>";
    unset($heroes);
    $heroes[] = new Mage("the Nine-Tailed Fox","Ahri",
                array("Orb of Deception","Fox-Fire","Charm","Spirit Rush"));
    $heroes[] = new Assassin("九尾妖狐","阿狸",
                array("欺诈宝珠","妖异狐火","魅惑妖术","灵魄突袭"));
    $heroes[] = new Fighter("the Grand Duelist","Fiora",
                array("Lunge","Riposte","Bladework","Grand Challenge"));
    $heroes[] = new Marksman("the Frost Archer","Ashe",
                array("Ranger's Focus","Volley","Hawkshot","Enchanted Crystal Arrow"));
    $heroes[] = new Support("the Chain Warden","Thresh",array());
    echo $heroes[0]::getAmount();
    foreach($heroes as $hero)
    {
        echo $hero;
    }
}

interface Alibity
{
    public function set_abilities(array $abilities);
}

//英雄
class Hero implements Alibity
{
    public $nick_name;
    public $name;
    private $abilities = array();
    const amount = 126;
    
    function __construct($nname,$name,array $ab)
    {
        $this->nick_name = $nname;
        $this->name = $name;
        $this->abilities = $ab;
    } 
    function __destruct()
    {
        echo "Destroying " . $this->name . "<br>";
    }
    function set_abilities(array $abilities)
    {
        $this->abilities = $abilities;
    }
    function getAmount()
    {
        return "<p>英雄总数：".self::amount."</p>";
    }
    function __toString()
    {
        $str = get_class($this).": ";
        $str .= "\t nick_name: $this->nick_name";
        $str .= "\t name: $this->name";
        if(!empty($this->abilities))
        {
            $str .= "\t abilities:";
            foreach($this->abilities as $ability)
            {
                $str .= "\t $ability,";
            }
        }
        $str .= "<br>";
        return $str;
    }
}

//Traits 是一种为类似 PHP 的单继承语言而准备的代码复用机制。
trait Construct
{
    function __construct($nname,$name,array $ab)
    {
        parent::__construct($nname,$name,$ab);
    }
}

//刺客 Ahri Akali Fizz Katarina Yi Talon Vayne Vi Zed
class Assassin extends Hero
{
    use Construct;
}
//战士 Darius Fiora Garen Irelia Jax Renekton Riven Ryze Wukong Yasuo
class Fighter extends Hero
{
    use Construct;
}
//法师 Ahri Annie Diana Katarina LeBlanc Morgana 
class Mage extends Hero
{
    use Construct;
}
//辅助 Alistar Braum Janna Leona LuLu Lux Nami Nunu Sona Soraka Thresh
class Support extends Hero
{
    use Construct;
}
//坦克 Alistar Braum Mundo Garen Leona Malphite Maokai Nasus Nautilus Olaf
class Tank extends Hero
{
    use Construct;
}
//射手 Ashe Caitlyn Draven Ezreal Jinx Lucian Sivir Tristana Vayne
class Marksman extends Hero
{
    use Construct;
}
?>
<?php
//分派请求
function dispatch_request()
{
    if(isset($_GET["action"]))
    {
        $action = $_GET["action"];
        if($action == "add")
        {
            add();
        }
        else if($action == "cnt_mysql")
        {
            cnt_mysql();
        }
        else
        {
            echo "Wrong action response";
        }
        die(0);
    }
}
//定义响应函数
function add()
{
    $a = test_input($_POST["a"]);
    $b = test_input($_POST["b"]);
    echo $a + $b;
}

function test_input($data)
{
    $data = trim($data);                //去掉空白
    $data = stripslashes($data);        //去掉转义符
    return htmlspecialchars($data);     //替换预定义符号为HTML实体
}

//连接数据库
function cnt_mysql()
{
    $con = mysqli_connect("localhost","","","test");
    if (mysqli_connect_errno($con))
    {
        echo "连接MySQL失败: " . mysqli_connect_error();
    }
    else
    {
        echo "成功连接MySQL";
    }
    mysqli_close($con);
}
?>
<h2><?php echo GREETING;?></h2>
<?php include "navi.php";?>
<p><?php echo "访问次数：",$count," 时间：",date("Y/m/d");?></p>

<div id="tabs">
	<ul>
		<li><a href="#tabs-1">Hello</a></li>
		<li><a href="#tabs-2">Class</a></li>
		<li><a href="#tabs-3">Form</a></li>
		<li><a href="#tabs-4">Regex</a></li>
		<li><a href="#tabs-5">MySQL</a></li>
	</ul>
	<div id="tabs-1"><?php hello($b);?></div>
	<div id="tabs-2"><?php test_class();?></div>
	<div id="tabs-3">
        <form action="index.php" method="post">
        A: <input id="id_a" type="number" name="a">
        B: <input id="id_b" type="number" name="b">
        <input type="button" value="计算" onclick=calc()>
        </form>
        <p>计算结果:<span id='res'></span></p>
        <script type="text/javascript">
            function calc(){
                var a = document.getElementById('id_a').value;
                var b = document.getElementById('id_b').value;
                if (!a || a==0 || !b || b==0) return;
                
                $.post("?action=add",{'a':a,'b':b}, function(ret){
                    $('#res').html(ret)
                })
            }
        </script>
    </div>
	<div id="tabs-4">
        <?php
        $url = "http://www.php.net/index.html";
        if(preg_match('@^(?:http://)?(?:[^.]+\.)?([^.]+\.[^./]+)@i',$url, $matches))
        {
            echo "<p>preg_match 获取URL($url)中的域名:$matches[1]</p>";//var_dump($matches);
        }

        if(preg_match('/(?<!c)d(?=e)/', 'abrde', $matches))
        {
            echo "<p>存在前面不紧跟c, 后面紧跟e的d（测试预查通配符）</p>";
        }

        if(preg_match('#<(?P<name>\w+>)\w*</(?P=name)#', '<a>abc</a>', $matches))
        {
            echo "<p>HTML标签（测试命名通配符）</p>";
        }
        ?>
    </div>
	<div id="tabs-5">
        <button id="cnt">连接MySQL</button>
        <p id="res_mysql"></p>
    </div>
</div>
<script>
$().ready(function(){
    $("#tabs").tabs();
    $("#cnt").click(function(){
        $.post("?action=cnt_mysql", function(ret){
            $('#res_mysql').html(ret)
        });
    });
});
</script>
</body>
</html>